package suo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration parseMapper(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> mapper = rootElement.selectNodes("//mapper");
        String namespace = mapper.get(0).attributeValue("namespace");
        HashMap<String, MapperStatement> map = new HashMap<String, MapperStatement>();

        List<Element> list = rootElement.selectNodes("//select");
        getMapperStatement(list, "select", namespace, map);
        List<Element> updateEles = rootElement.selectNodes("//update");
        getMapperStatement(updateEles, "update", namespace, map);

        configuration.setMapperStatementMap(map);
        return configuration;
    }

    private void getMapperStatement(List<Element> list, String type, String namespace, Map<String, MapperStatement> map) throws ClassNotFoundException {
        if (list != null && list.size() != 0) {
            for (Element element : list) {
                String id = element.attributeValue("id");
                String paramterType = element.attributeValue("paramterType");
                String resultType = element.attributeValue("resultType");
                Class<?> paramterClass = Class.forName(paramterType);
                Class<?> resultClass = Class.forName(resultType);
                String sql = element.getTextTrim();
                MapperStatement mapperStatement = new MapperStatement(id, sql, paramterClass, resultClass, type);
                String key = namespace + "." + id;
                map.put(key, mapperStatement);
            }
        }
    }
}
